package com.bbzn.device.client.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bbzn.device.client.constant.CwtingConstant;
import com.bbzn.device.client.dto.ct.data.GeneralPayload;
import com.bbzn.device.client.dto.ct.data.YgPayload;
import com.bbzn.device.client.dto.ct.data.YgServiceData;
import com.bbzn.device.client.dto.ct.response.TupDataReport;
import com.bbzn.device.client.service.CwtingMessageStrategy;
import com.bbzn.device.client.service.RabbitService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;

/**
 * @Author wulongbo
 * @Date 2021/9/22 10:27
 * @Version 1.0
 */

@Component
@Slf4j
public class DataReportTupUnionStrategy implements CwtingMessageStrategy {

    @Autowired
    private RabbitService rabbitService;

    @Override
    public void pushMessage(JSONObject jsonObject) throws Exception {
        log.info("TUP合并数据变化");
        TupDataReport tupDataReport = JSONObject.toJavaObject(jsonObject, TupDataReport.class);
        Object payload = tupDataReport.getPayload();
        //JSONArray
        List<YgPayload> payloadArray = JSONArray.parseArray(payload.toString(), YgPayload.class);
        payloadArray.stream().forEach(
                ygPayload -> {
                    if (ygPayload == null) {
                        return;
                    }
                    if (!StringUtils.equals("Alarm", ygPayload.getServiceId())) {
                        return;
                    }
                    YgServiceData ygServiceData = ygPayload.getServiceData();
                    if (ygServiceData == null) {
                        return;
                    }
                    log.info("alarmCode:" + ygServiceData.getAlarmCode());
                    GeneralPayload generalPayload = new GeneralPayload();
                    generalPayload.setIMEI(tupDataReport.getIMEI());
                    generalPayload.setAlarmCode(ygServiceData.getAlarmCode());
                    generalPayload.setDeviceType(ygServiceData.getDeviceType());
                    try {
                        rabbitService.send(JSON.toJSONString(generalPayload), new HashMap<>(), CwtingConstant.QUEUE_YG_NOTIFY, CwtingConstant.EXCHANGE_YG_NOTIFY);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
        );
    }
}
